package com.twu.biblioteca.library;

import com.twu.biblioteca.category.CategoryManager;
import com.twu.biblioteca.message.Message;
import com.twu.biblioteca.user.User;
import com.twu.biblioteca.user.Users;
import com.twu.biblioteca.utils.IO;

/**
 * Created by Enrico on 10/09/2014.
 */
public class Library {

    private Catalogue catalogue;
    private Users users;

    public Library(){
        this.catalogue = new Catalogue();
        this.users = new Users();
    }

    public void setup() {
        showWelcomeMsg();
        build();
    }

    public void build(){
        char choice = validChoice();
        while(!isExit(choice)){
            menu(choice);
            choice = validChoice();
        }
    }

    public void menu(char choice){
        switch(choice){
            case 'l':
                login(read("Library Number"));
                break;
            case 'b':
                catalogue.showBooks();
                break;
            case 'm':
                catalogue.showMovies();
                break;
        }
    }

    public char validChoice(){
        char choice = readChoice();
        while(!valid(choice)){
            explainError();
            choice = readChoice();
        }
        return choice;
    }

    public void showWelcomeMsg(){
        System.out.println(Message.WELCOME.getText());
    }

    public char readChoice() {
        System.out.print("\nLogin, List Books, List Movies or Exit (l/b/m/x): ");
        return Character.toLowerCase(IO.nextChar());
    }

    public boolean valid(char choice) {
        String choices = "lbmx";
        return choices.contains(Character.toString(choice));
    }

    private void explainError(){
        System.out.println("Select a valid option!");
    }

    public boolean isExit(char choice) {
        return choice == 'x';
    }

    public void showError() {
        System.out.println("Invalid login, please try again.");
    }

    public void login(String libraryNo) {
        login(libraryNo, read("Password"));
    }

    public void login(String libraryNo, String password) {
        User user = lookup(libraryNo, password);

        if (user != null)
            showCategoriesTo(user);
        else
            showError();
    }

    public String read(String input) {
        System.out.print("\tInsert your " + input + ": ");
        return IO.nextLine();
    }

    public User lookup(String libraryNo, String password){
        return users.lookup(libraryNo, password);
    }

    public void showCategoriesTo(User user){
        CategoryManager categoryMgt = new CategoryManager(catalogue);
        categoryMgt.setup(user);
    }
}
